package util

import (
	"gitee.com/kubage88/wf-deploy-plugin-javax/consts"
	"os/exec"
	"runtime"
	"strings"
)

func buildCmdText(commandName string, params ...string) string {
	cmdText := commandName + consts.BLANK_SEPARATOR + strings.Join(params, consts.BLANK_SEPARATOR)
	osType := strings.ToLower(runtime.GOOS)
	if osType != "windows" {
		cmdText = cmdText + consts.LINUX_BACKGROUND_SUFFIX
	}

	return cmdText
}

func buildCmdObject(commandName string, params ...string) *exec.Cmd {
	osType := strings.ToLower(runtime.GOOS)
	cmdText := buildCmdText(commandName, params...)
	if osType == "windows" {
		return exec.Command("cmd.exe", "/c", "start /b "+cmdText)
	}

	return exec.Command("/bin/bash", "-c", cmdText)
}

func Exec(commandName string, params ...string) error {
	//函数返回一个*Cmd，用于使用给出的参数执行name指定的程序
	cmd := buildCmdObject(commandName, params...)
	err := cmd.Start()
	return err
}
